<template>
	<view class="todo-container">
		<!-- 主页时间信息+搜索面板 -->
		<user-panel 
			:username="username"
			:userAvatar="userAvatar"
			:completedCount="completedCount"
			:totalCount="todoItems.length"
			@search="openSearchPopup"
			@add="openAddPopup"
		/>
		
		<!-- 日期选择触发区域 -->
		<view class="date-selector-bar" @tap="openDatePicker">
			<!-- 留空，与原型图一致 -->
		</view>
		
		<!-- 待办事项列表 -->
		<view class="todo-list-container">
			<scroll-view scroll-y class="todo-list">
				<view v-if="todoItems.length === 0" class="empty-list">
					<text class="empty-text">您还没有添加任何待办事项</text>
				</view>
				<block v-else>
					<view class="todo-list-wrapper">
						<todo-item 
							v-for="(item, index) in todoItems" 
							:key="index"
							:todo="item"
							:index="index"
							ref="todoItems"
							@status-change="updateItemStatus"
							@edit="editItem"
							@delete="deleteItem"
							@tap="handleItemTap"
							@slide="handleItemSlide"
						/>
					</view>
				</block>
				
				<!-- 添加事项按钮 -->
				<view class="add-todo-btn" @click="openAddPopup">
					<image src="/static/index主页/plus.1@2x.png" mode="aspectFit" class="add-icon"></image>
					<text class="add-text">添加事项</text>
				</view>
			</scroll-view>
		</view>
		
		<!-- 搜索弹窗 -->
		<search-popup 
			:visible.sync="searchPopupVisible"
			:dataSource="todoItems"
			@select="handleSearchSelect"
		/>
		
		<!-- 日期选择下拉 -->
		<view class="date-picker-dropdown" v-if="datePickerVisible">
			<view class="date-picker-overlay" @tap="closeDatePicker"></view>
			<view class="date-picker-content">
				<!-- 星期表头 -->
				<view class="date-picker-week-header">
					<view class="week-day" v-for="(day, index) in ['周日','周一','周二','周三','周四','周五','周六']" :key="index">
						<text>{{day}}</text>
					</view>
				</view>
				
				<!-- 日期网格 -->
				<view class="date-picker-days">
					<!-- 上月日期 -->
					<view class="day-cell" v-for="(i, index) in 6" :key="index">
						<view class="day-button prev-month">
							<text class="solar-date">{{30-6+i}}</text>
							<text class="lunar-date">廿{{i+3}}</text>
						</view>
					</view>
					
					<!-- 当月日期 -->
					<view class="day-cell" v-for="(i, index) in 30" :key="index + 10">
						<view :class="{'day-button': true, 'current-month': true, 'selected': i === 18, 'today': i === 18}">
							<text class="solar-date">{{i < 10 ? '0' + i : i}}</text>
							<text class="lunar-date">{{getLunarDay(i)}}</text>
						</view>
					</view>
					
					<!-- 下月日期 -->
					<view class="day-cell" v-for="(i, index) in 6" :key="index + 50">
						<view class="day-button next-month">
							<text class="solar-date">{{i < 10 ? '0' + i : i}}</text>
							<text class="lunar-date">初{{i}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 添加/编辑待办事项弹窗 -->
		<add-item-popup 
			:visible.sync="addItemPopupVisible"
			:editingItem="editingItem"
			:editingIndex="editingIndex"
			@add="addNewItem"
			@update="updateItem"
		/>
		
		<!-- 用户面板弹窗 -->
		<view class="user-panel-popup" v-if="userPanelVisible">
			<view class="popup-mask" @click="closeUserPanel"></view>
			<view class="user-panel-content">
				<!-- 头像和用户名 -->
				<view class="user-info">
					<view class="avatar-wrapper">
						<image class="avatar-image" :src="userAvatar"></image>
					</view>
					<view class="username">{{username}}</view>
				</view>
				
				<!-- 菜单选项 -->
				<view class="menu-list">
					<view class="menu-item">
						<text>服务与协议</text>
					</view>
					<view class="menu-item">
						<text>用户隐私</text>
					</view>
					<view class="menu-item">
						<text>清理缓存</text>
					</view>
					<view class="menu-item" @click="logout">
						<text>登出账号</text>
					</view>
				</view>
				
				<!-- VIP区域 -->
				<view class="vip-section">
					<view class="vip-text">
						<text class="vip-label">VIP</text>
						<text class="vip-desc">订阅高级版本</text>
					</view>
					<view class="vip-arrow">→</view>
				</view>
			</view>
		</view>
		
		<!-- 左侧菜单 -->
		<view class="left-menu-popup" v-if="leftMenuVisible">
			<view class="popup-mask" @click="closeLeftMenu"></view>
			<view class="left-menu-content">
				<view class="menu-list">
					<view class="menu-item">
						<view class="menu-icon">
							<image src="/static/侧边栏/编组 11-1@2x.png" mode="aspectFit" class="menu-icon-image"></image>
						</view>
						<text class="menu-text">历史</text>
					</view>
					<view class="menu-item">
						<view class="menu-icon">
							<image src="/static/侧边栏/编组 11-2@2x.png" mode="aspectFit" class="menu-icon-image"></image>
						</view>
						<text class="menu-text">列表</text>
					</view>
					<view class="menu-item">
						<view class="menu-icon">
							<image src="/static/侧边栏/编组 11-3@2x.png" mode="aspectFit" class="menu-icon-image"></image>
						</view>
						<text class="menu-text">颜色标签</text>
					</view>
					<view class="menu-item">
						<view class="menu-icon">
							<image src="/static/侧边栏/编组 11-4@2x.png" mode="aspectFit" class="menu-icon-image"></image>
						</view>
						<text class="menu-text">回收站</text>
					</view>
					<view class="menu-item">
						<view class="menu-icon">
							<image src="/static/侧边栏/编组 11-5@2x.png" mode="aspectFit" class="menu-icon-image"></image>
						</view>
						<text class="menu-text">设置</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import UserPanel from './UserPanel.vue';
	import TodoItem from './TodoItem.vue';
	import SearchPopup from './SearchPopup.vue';
	import AddItemPopup from './AddItemPopup.vue';
	import DatePicker from './DatePicker.vue';
	
	export default {
		name: "TodoList",
		components: {
			UserPanel,
			TodoItem,
			SearchPopup,
			AddItemPopup,
			DatePicker
		},
		props: {
			username: {
				type: String,
				default: '用户'
			},
			userAvatar: {
				type: String,
				default: '/static/index主页/avatar@2x.png'
			},
			initialItems: {
				type: Array,
				default: () => []
			}
		},
		data() {
			return {
				todoItems: [],
				searchPopupVisible: false,
				addItemPopupVisible: false,
				userPanelVisible: false,
				leftMenuVisible: false,
				editingItem: null,
				editingIndex: -1,
				datePickerVisible: false,
				debounceTimer: null
			}
		},
		computed: {
			completedCount() {
				return this.todoItems.filter(item => item.status === 1).length;
			}
		},
		watch: {
			// 监听初始数据变化
			initialItems: {
				handler(val) {
					// 深拷贝避免直接修改props
					this.todoItems = JSON.parse(JSON.stringify(val));
				},
				immediate: true,
				deep: true
			},
			
			// 当数据变化时通知父组件
			todoItems: {
				handler(val) {
					// 使用防抖避免频繁触发
					if (this.debounceTimer) {
						clearTimeout(this.debounceTimer);
					}
					this.debounceTimer = setTimeout(() => {
						this.$emit('items-change', JSON.parse(JSON.stringify(val)));
					}, 300);
				},
				deep: true
			}
		},
		mounted() {
			// 监听全局事件
			uni.$on('openUserPanel', () => {
				this.openUserPanel();
			});
			
			// 监听打开左侧菜单事件
			uni.$on('openLeftMenu', () => {
				this.openLeftMenu();
			});
		},
		beforeDestroy() {
			// 组件销毁时解除事件监听
			uni.$off('openUserPanel');
			uni.$off('openLeftMenu');
		},
		methods: {
			openSearchPopup() {
				this.searchPopupVisible = true;
			},
			
			openAddPopup() {
				this.editingItem = null;
				this.editingIndex = -1;
				this.addItemPopupVisible = true;
			},
			
			openUserPanel() {
				this.userPanelVisible = true;
			},
			
			closeUserPanel() {
				this.userPanelVisible = false;
			},
			
			openLeftMenu() {
				this.leftMenuVisible = true;
			},
			
			closeLeftMenu() {
				this.leftMenuVisible = false;
			},
			
			logout() {
				// 跳转到登录页面
				uni.navigateTo({
					url: '/pages/login/login'
				});
				this.closeUserPanel();
			},
			
			addNewItem(newItem) {
				// 检查是否已存在相同标题和内容的项
				const isDuplicate = this.todoItems.some(item => 
					(item.userDate === newItem.userDate || item.userName === newItem.userName) &&
					item.content === newItem.content
				);
				
				if (isDuplicate) {
					uni.showToast({
						title: '已存在相同的待办事项',
						icon: 'none'
					});
					return;
				}
				
				// 添加新项目
				this.todoItems.unshift(newItem);
			},
			
			updateItemStatus({ todo, index }) {
				// 检查状态是否真的发生变化，避免不必要的更新
				if (this.todoItems[index].status === todo.status) return;
				
				// 创建新对象以避免直接修改原始对象
				const updatedItems = [...this.todoItems];
				updatedItems[index] = { ...todo };
				this.todoItems = updatedItems;
			},
			
			editItem({ todo, index }) {
				this.editingItem = { ...todo };
				this.editingIndex = index;
				this.addItemPopupVisible = true;
			},
			
			updateItem({ item, index }) {
				// 创建新对象以避免直接修改原始对象
				const updatedItems = [...this.todoItems];
				updatedItems[index] = { ...item };
				this.todoItems = updatedItems;
				
				// 重置编辑状态
				this.editingItem = null;
				this.editingIndex = -1;
			},
			
			deleteItem({ index }) {
				// 先关闭编辑弹窗（如果打开）
				if (this.editingIndex === index) {
					this.editingItem = null;
					this.editingIndex = -1;
				}
				
				// 延迟删除以避免潜在的状态问题
				setTimeout(() => {
					const updatedItems = [...this.todoItems];
					updatedItems.splice(index, 1);
					this.todoItems = updatedItems;
				}, 0);
			},
			
			handleSearchSelect(index) {
				this.editingItem = { ...this.todoItems[index] };
				this.editingIndex = index;
				this.addItemPopupVisible = true;
			},
			
			handleItemTap({ index }) {
				this.editingItem = { ...this.todoItems[index] };
				this.editingIndex = index;
				this.addItemPopupVisible = true;
			},
			
			handleItemSlide(index) {
				// 当一个项目被滑动时，将通知TodoItem组件重置其他项目
				if (this.$refs.todoItems) {
					// $refs.todoItems可能是数组的数组，需要进行扁平化处理
					const todoItems = Array.isArray(this.$refs.todoItems) ? 
						(Array.isArray(this.$refs.todoItems[0]) ? 
							this.$refs.todoItems.flat() : 
							this.$refs.todoItems) : 
						[];
					
					todoItems.forEach((item, idx) => {
						if (idx !== index && item && typeof item.resetActions === 'function') {
							item.resetActions();
						}
					});
				}
			},
			
			openDatePicker() {
				this.datePickerVisible = true;
			},
			
			closeDatePicker() {
				this.datePickerVisible = false;
			},
			
			confirmDateSelection() {
				// 这里只是样式展示，不实现实际逻辑
				this.closeDatePicker();
			},
			
			getLunarDay(day) {
				// 模拟农历日期，实际应用中应使用农历转换算法
				const lunarDays = ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十',
					'十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十',
					'廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十'];
				return lunarDays[day - 1];
			}
		}
	}
</script>

<style scoped>
	.todo-container {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #fff;
	}
	
	.todo-list-container {
		flex: 1;
		overflow: hidden;
		padding: 30rpx;
		box-sizing: border-box;
		background-color: #f8f8f8;
	}
	
	.todo-list {
		height: 100%;
		width: 100%;
		box-sizing: border-box;
	}
	
	.todo-list-wrapper {
		padding-bottom: 80rpx;
	}
	
	.empty-list {
		height: 300rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
	
	/* 用户面板弹窗样式 */
	.user-panel-popup {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 999;
	}
	
	.popup-mask {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.3);
	}
	
	.user-panel-content {
		position: fixed;
		left: 0;
		width: 100%;
		background-color: #fff;
		z-index: 1000;
		display: flex;
		flex-direction: column;
		padding: 30rpx 0;
		border-radius: 20rpx 20rpx 0 0;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
		bottom: 0;
		animation: slideUp 0.3s ease-out forwards;
	}
	
	@keyframes slideUp {
		from {
			transform: translateY(100%);
		}
		to {
			transform: translateY(0);
		}
	}
	
	.user-info {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 40rpx 0 30rpx;
	}
	
	.avatar-wrapper {
		width: 150rpx;
		height: 150rpx;
		border-radius: 50%;
		overflow: hidden;
		margin-bottom: 20rpx;
		background-color: #fff;
		border: 1rpx solid #eee;
		position: relative;
	}
	
	.avatar-wrapper::before {
		content: "";
		position: absolute;
		top: -6rpx;
		left: -6rpx;
		right: -6rpx;
		bottom: -6rpx;
		border-radius: 50%;
		border: 1px solid #eee;
	}
	
	.avatar-wrapper::after {
		content: "";
		position: absolute;
		top: -12rpx;
		left: -12rpx;
		right: -12rpx;
		bottom: -12rpx;
		border-radius: 50%;
		border: 1px solid #f5f5f5;
	}
	
	.avatar-image {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}
	
	.username {
		font-size: 36rpx;
		font-weight: 500;
		color: #333;
		margin-top: 20rpx;
	}
	
	.menu-list {
		width: 100%;
	}
	
	.menu-item {
		padding: 28rpx 0;
		font-size: 30rpx;
		color: #333;
		border-bottom: 1rpx solid #f5f5f5;
		text-align: center;
	}
	
	.vip-section {
		width: 100%;
		padding: 25rpx 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 20rpx;
		box-sizing: border-box;
	}
	
	.vip-text {
		display: flex;
		align-items: center;
	}
	
	.vip-label {
		background-color: #007AFF;
		color: #fff;
		padding: 4rpx 16rpx;
		border-radius: 8rpx;
		font-size: 26rpx;
		margin-right: 15rpx;
		font-weight: bold;
	}
	
	.vip-desc {
		font-size: 28rpx;
		color: #333;
	}
	
	.vip-arrow {
		color: #007AFF;
		font-size: 30rpx;
		font-weight: bold;
	}
	
	/* 左侧菜单弹窗样式 */
	.left-menu-popup {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 999;
	}
	
	.left-menu-content {
		position: fixed;
		left: 0;
		width: 100%;
		background-color: #fff;
		z-index: 1000;
		display: flex;
		flex-direction: column;
		padding: 30rpx 0;
		border-radius: 20rpx 20rpx 0 0;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
		bottom: 0;
		animation: slideUp 0.3s ease-out forwards;
	}
	
	@keyframes slideUp {
		from {
			transform: translateY(100%);
		}
		to {
			transform: translateY(0);
		}
	}
	
	.left-menu-content .menu-list {
		padding: 20rpx 0;
	}
	
	.left-menu-content .menu-item {
		display: flex;
		align-items: center;
		padding: 25rpx 40rpx;
		text-align: left;
	}
	
	.menu-icon {
		margin-right: 20rpx;
		width: 50rpx;
		height: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.menu-icon-image {
		width: 100%;
		height: 100%;
	}
	
	.menu-text {
		font-size: 30rpx;
		color: #333;
	}
	
	/* 列表底部添加事项按钮 */
	.add-todo-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 90rpx;
		background-color: #fff;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
		margin-bottom: 20rpx;
	}
	
	.add-icon {
		width: 36rpx;
		height: 36rpx;
		margin-right: 10rpx;
	}
	
	.add-text {
		font-size: 30rpx;
		color: #007AFF;
	}
	
	/* 日期选择下拉样式 */
	.date-picker-dropdown {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 1000;
	}
	
	.date-picker-overlay {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.1);
	}
	
	.date-picker-content {
		position: absolute;
		top: 380rpx; /* 调整位置到日期选择按钮的正下方 */
		left: 30rpx;
		right: 30rpx;
		background-color: #fff;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		padding-bottom: 20rpx;
		z-index: 1001;
		border-radius: 16rpx; /* 添加圆角 */
		overflow: hidden; /* 确保内容不超出圆角边框 */
	}
	
	.date-picker-week-header {
		display: flex;
		justify-content: space-around;
		background-color: #fff;
		padding: 30rpx 0 20rpx;
	}
	
	.week-day {
		width: 14.28%;
		text-align: center;
		font-size: 24rpx;
		color: #666;
	}
	
	.date-picker-days {
		display: flex;
		flex-wrap: wrap;
		padding: 0 10rpx;
	}
	
	.day-cell {
		width: 14.28%;
		height: 100rpx;
		padding: 5rpx;
		box-sizing: border-box;
	}
	
	.day-button {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
	}
	
	.solar-date {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 6rpx;
	}
	
	.lunar-date {
		font-size: 20rpx;
		color: #999;
	}
	
	.day-button.prev-month .solar-date,
	.day-button.next-month .solar-date {
		color: #ccc;
	}
	
	.day-button.prev-month .lunar-date,
	.day-button.next-month .lunar-date {
		color: #ddd;
	}
	
	.day-button.selected {
		position: relative;
	}
	
	.day-button.selected .solar-date {
		color: #fff;
	}
	
	.day-button.selected .lunar-date {
		color: #fff;
	}
	
	.day-button.selected::after {
		content: "";
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 70rpx;
		height: 70rpx;
		background-color: #007AFF;
		border-radius: 8rpx;
		z-index: -1;
	}
	
	/* 日期选择触发区域样式 */
	.date-selector-bar {
		left: 30rpx;
		right: 30rpx;
		background-color: #eee;
		margin: 0 auto;
		border-radius: 4rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 20rpx;
		cursor: pointer;
		border: 1px solid #eee;
		left: 168px;
		width: 40px;
		opacity: 1;
		border-radius: 2px;
		background: rgba(238, 238, 238, 1);

	}
</style> 